#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>

const int size = 1024;

std::string GetOtherMessage()
{
    static int cnt = 0;
    std::string messageid = std::to_string(cnt);
    cnt++;
    pid_t self_id = getpid();
    std::string stringpid = std::to_string(self_id);

    std::string message =  "messageid: ";
    message += messageid;
    message += "my pid is: ";
    message += stringpid;

    return message;
}

void SubProcessWrite(int wfd)
{
    std::string message = "father, I am your son process!";
    while (true)
    {
        std::string info = message + GetOtherMessage();
        write(wfd, info.c_str(), info.size());   //写入管道的时候，没有写入'\0'，且没有必要
        sleep(1);
    }
}

void FatherProcessRead(int rfd)
{
    char inbuffer[size];//  c99, gnu g99
    while (true)
    {
        ssize_t n = read(rfd, inbuffer, sizeof(inbuffer) - 1);
        if (n > 0)
        {
            inbuffer[n] = 0;
            std::cout << "father get message: " << inbuffer << std::endl;
        }
        //
    }
}

int main()
{
    //1.创建管道
    int pipefd[2];
    int n = pipe(pipefd);
    if (n != 0)
    {
        std::cout << "errno" << errno << "errstring : " << strerror(errno) << std::endl;
        return 1; 
    }
    //pipefd[0]->r  pipefd[1]->w
    std::cout << "pipefd[0] :" << pipefd[0] << ", pipefd[1] :" << pipefd[1] << std::endl;
    sleep(1);
    //2.创建子进程
    pid_t id = fork();
    if (id == 0)
    {
        std::cout << "子进程关闭了不需要的fd了, 准备发消息了"<< std::endl;
        sleep(1);
        //子进程
        close(pipefd[0]);
        SubProcessWrite(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }
    //父进程
    std::cout << "父进程关闭了不需要的fd了, 准备收消息了"<< std::endl;
    sleep(1);
    close(pipefd[1]);
    FatherProcessRead(pipefd[0]);

    close(pipefd[0]);
    pid_t rid = waitpid(id, nullptr, 0);
    if (rid > 0)
    {
        std::cout << "wait child process done" << std::endl;
    }
    return 0;
}